Bootstrap demo

Python Strings: Comprehensive Notes

Table of Contents

1. Introduction to Strings

In Python, a string is a sequence of characters enclosed within single quotes ('), double quotes ("), or triple quotes (''' or """). Strings are immutable, meaning once created, their content cannot be changed. They are one of the most commonly used data types for representing text.

# String examples
s1 = 'Hello, World!'
s2 = "Python Programming"
s3 = '''This is a
multi-line string.'''

2. String Creation and Basic Operations

Strings can be created directly by assigning a sequence of characters to a variable. Basic operations include concatenation (+), repetition (*), and membership testing (in).

Examples:

# Concatenation
a = "Hello"
b = "World"
print(a + " " + b) # Output: Hello World

# Repetition
print("Hi" * 3) # Output: HiHiHi

# Membership
print('e' in 'Hello') # Output: True

3. String Indexing and Slicing

Strings support indexing (accessing individual characters) and slicing (accessing substrings). Indexing starts at 0, and negative indices count from the end.

Examples:

s = "Python"

# Indexing
print(s[0]) # Output: P
print(s[-1]) # Output: n

# Slicing [start:stop:step]
print(s[1:4]) # Output: yth
print(s[::2]) # Output: Pto
print(s[::-1]) # Output: nohtyP (reverse)

4. String Methods and Library Functions

Python provides numerous built-in methods for string manipulation:

Method Description Example
str.upper() Converts to uppercase "hello".upper() → "HELLO"
str.lower() Converts to lowercase "HELLO".lower() → "hello"
str.strip() Removes leading/trailing whitespace " hi ".strip() → "hi"
str.split(sep) Splits string into list by separator "a,b,c".split(",") → ['a','b','c']
str.join(iterable) Joins iterable elements with string ",".join(['a','b']) → "a,b"
str.replace(old, new) Replaces occurrences of substring "hello".replace('l','x') → "hexxo"
str.find(sub) Returns index of first occurrence "hello".find('e') → 1
str.startswith(prefix) Checks if string starts with prefix "hello".startswith('he') → True
str.endswith(suffix) Checks if string ends with suffix "hello".endswith('lo') → True
str.isalpha() Checks if all characters are alphabetic "abc".isalpha() → True
str.isdigit() Checks if all characters are digits "123".isdigit() → True
str.isalnum() Checks if alphanumeric "a1b2".isalnum() → True

5. String Formatting

Python offers multiple ways to format strings:

f-strings (Python 3.6+):

name = "Alice"
age = 25
print(f"{name} is {age} years old.") # Output: Alice is 25 years old.

str.format():

print("{} is {} years old.".format(name, age))

% formatting (older style):

print("%s is %d years old." % (name, age))

6. Common String Operations

Escape Sequences:

print("Line1\nLine2") # Output with newline
print("Tab\tseparated") # Output with tab

Raw Strings:

print(r"Line1\nLine2") # Output: Line1\nLine2
print(r"C:\Users\Documents") # Output: C:\Users\Documents

String Length:

print(len("Hello")) # Output: 5

7. Practical Examples

Example 1: Reversing a String

s = "engineering"
reversed_s = s[::-1]
print(reversed_s) # Output: gnireenigne

Example 2: Counting Vowels

s = "Hello, World!"
vowels = "aeiouAEIOU"
count = sum(1 for char in s if char in vowels)
print(count) # Output: 3

Example 3: Palindrome Check

def is_palindrome(s):
    s = s.lower().replace(" ", "")
    return s == s[::-1]

print(is_palindrome("Madam")) # Output: True

Example 4: Extracting Domain from Email

email = "user@example.com"
domain = email.split('@')[1]
print(domain) # Output: example.com
Note: These notes cover the fundamentals of strings in Python. Practice these concepts to strengthen your understanding!